package com.glorystone.ins.controller;


import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.google.common.collect.Lists;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.glorystone.ins.common.AesEncryptUtil;
import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.domain.SysRole;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.ISysRoleService;
import com.glorystone.ins.service.ISysUserService;
import com.glorystone.ins.util.PasswordHelper;


/**
 * Created by chenshiyu on 2018/3/6
 * @author chenshiyu
 */
@Controller
@RequestMapping("/sysuser")
public class SysUserController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;
    
    @Value("${InternalUserPassword}")
    private String InternalUserPassword;
    
    @Value("${externalUserPassword}")
    private String externalUserPassword;
    
    
    @RequestMapping("/tolist")
    public ModelAndView tolist(ModelAndView mv){
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	if(user.getUserLevel()==1){
    		List<Map<String, Object>> officeList = sysRoleService.getAllDepartment();
    		mv.addObject("officeList", officeList);
    		mv.addObject("result", 1);
    		mv.setViewName("system/userList");
    		return mv;
    	}else{
    		mv.addObject("office", user);
    		mv.addObject("result", 2);
    		mv.setViewName("system/userList");
    		return mv;
    	}
    }

    
    /**
     * 组装内部用户列表数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/queryTableData")
    @ResponseBody
    public DataTable<SysUser> queryTableData(HttpServletRequest request) {
        PageVo vo =  parametToPageVo(request,SysUser.class);
        PageList<SysUser> list = sysUserService.findUserList(vo);
        DataTable data = resultToDataTable(list);
        log.info("------返回结果data------"+data);
        return data;

    }
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/selectTableData")
    @ResponseBody
    public DataTable<SysUser> selectTableData(HttpServletRequest request){
    	PageVo vo = parametToPageVo(request,SysUser.class);
    	PageList<SysUser> userList = sysUserService.selectUser(vo);
    	DataTable data = resultToDataTable(userList);
    	log.info("------返回结果data------"+data);
    	return data;
    }


    /**
     * 去往编辑-用户
     */
    
	@RequestMapping("/toedit/{id}")
    @ResponseBody
    public SysUser toEdit(@PathVariable Long id){
		log.info("-------传入参数id------"+id);
    	SysUser user = sysUserService.getUserById(id);  
        return user;
    }
   
    /**
     * 添加/编辑-用户
     * @throws Exception 
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addUser(SysUser user) throws Exception {
    	log.info("-------传入参数user------"+user);
        if(user.getTid() != null && user.getTid() > 0){
        	String roleId = user.getRoleId();
        	StringBuffer sb = new StringBuffer();
        	sb.append(roleId).insert(0, "0,");
        	user.setRoleId(sb.toString());
            boolean result = sysUserService.updateUser(user);
            if(result){
            	return returnSuccess("操作成功！");
            }else{
            	return JsonResult.createErrorMsg("操作失败！");
            }
        }else{
        	 String roleId = user.getRoleId();
        	 StringBuffer sb = new StringBuffer();
        	 sb.append(roleId).insert(0, "0,");
        	 user.setRoleId(sb.toString());
        	 log.info("加完密后密码------------>"+user.getPassword());
        	 String password = AesEncryptUtil.desEncrypt(user.getPassword()).trim();
        	 log.info("解完密后密码------------>"+password);
        	 user.setPassword(password);
        	 SysUser u = PasswordHelper.encryptPassword(user);
        	 u.setType(0);
        	 u.setStatus(0);
        	 u.setRealName(user.getUsername());
            boolean result = sysUserService.addUser(u);
            if(result){
            	return returnSuccess("操作成功！");
            }else{
            	return JsonResult.createErrorMsg("操作失败！");
            }
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("/del/{id}")
    public @ResponseBody JsonResult delUser(@PathVariable Integer id){
        boolean result = sysUserService.delUser(Long.valueOf(id));
    	if(result){
    		return returnSuccess("操作成功！");
    	}else{
    		return JsonResult.createErrorMsg("操作失败！");
    	}
    }

    /**
     * 验证新增账号是否已经注册
     */
    @RequestMapping("/onlyOne")
    public @ResponseBody JsonResult onlyUser(String jobNumber){
        SysUser user = sysUserService.getUserByUserName(jobNumber);
        if(user==null){
            return returnSuccess("账号还没注册");
        }else{
            return JsonResult.createErrorMsg("账号已经注册");
        }
    }

    /**
     * 验证工号是否已被注册
     */
    @RequestMapping("/onlyJobNumber")
    public @ResponseBody JsonResult onlyJobNumber(String jobNumber){
    	log.info("-------传入参数jobNumber------"+jobNumber);
    	SysUser user = sysUserService.onlyJobNumber(jobNumber);
    	if(user==null){
            return returnSuccess("账号还没注册");
        }else{
            return JsonResult.createErrorMsg("账号已经注册");
        }
    }
    
    /**
     * 修改登录密码  oldpassword  password
     * @throws Exception 
     */
    @SuppressWarnings("unused")
	@RequestMapping(value = "/modifyPassword")
    public String modifyPassword(@RequestParam (value = "newPassword",required = true) String newPassword) throws Exception {
    	log.info("加密后新密码------------>"+newPassword);
    	String password = AesEncryptUtil.desEncrypt(newPassword).trim();
    	log.info("解密后新密码------------>"+password);
        SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
        log.info("user----------->"+user.getUsername());
        if(user == null){ 
            return "redirect:/index";
        }
        user.setPassword(password);
        SysUser u = PasswordHelper.encryptPassword(user);
        sysUserService.modifyPassword(user, u);
        //清空缓存
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }

    public static void  main(String[] strings){
        SysUser user = new SysUser();
        user.setUsername("admin");
        user.setPassword("admin");
        SysUser u = PasswordHelper.encryptPassword(user);
        log.info(u.getUsername()+" "+u.getPassword()+ " "+ u.getSalt() + " "+u.getCredentialsSalt());
    }

    /**
     * 修改用户状态
     * @param sysuser
     * @return
     */
    @RequestMapping(value = "/updateStatus")
    public @ResponseBody JsonResult updateStatus(SysUser sysuser){
    	log.info("-------传入参数sysuser------"+sysuser);
    	boolean result = sysUserService.updateStatus(sysuser);
    	if(result){
    		return returnSuccess("操作成功！");
    	}else{
    		return JsonResult.createErrorMsg("操作失败！");
    	}
    }
    
    /**
     * 查询相关角色
     * @param officeId
     * @return
     */
    @RequestMapping(value="/toSelectRole")
    @ResponseBody
    public Object toSelectRole(Long officeId){
    	log.info("-------传入参数officeId------"+officeId);
    	List<SysRole> roleList = sysRoleService.getRoleListByDepartmentId(officeId);
    	return roleList;
    }

    /**
     * 重置密码
     * @param user
     */
    @RequestMapping(value="/resetPassword")
    public @ResponseBody JsonResult resetPassword(Long id,String jobNumber,String message){
    	log.info("-------传入参数id------"+id+",------传入参数jobNumber------"+jobNumber+",------传入参数message------"+message);
    	SysUser user = new SysUser();
    	if(message.equals("0")){
    		user.setPassword(InternalUserPassword);
    	}else{
    		user.setPassword(externalUserPassword);
    	}
    	user.setTid(id);
    	user.setJobNumber(jobNumber);
    	SysUser u = PasswordHelper.encryptPassword(user);
    	boolean result = sysUserService.resetPassword(user,u);
    	if(result){
            return returnSuccess("操作成功");
        }else{
            return JsonResult.createErrorMsg("操作失败");
        }
    }
    
    
    @RequestMapping(value="/checkOldPassword")
    public @ResponseBody JsonResult checkOldPassword(@RequestParam (value = "oldPassword",required = true) String oldPassword) throws Exception{
    	log.info("加完密后原密码------------>"+oldPassword);
    	String password = AesEncryptUtil.desEncrypt(oldPassword).trim();
    	log.info("解密完后原密码------------>"+password);
    	SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
    	String saltPassword = user.getPassword();
    	user.setPassword(password);
    	String newPassword = new SimpleHash("md5",user.getPassword(),ByteSource.Util.bytes(user.getCredentialsSalt()),2).toHex();
    	if(newPassword.equals(saltPassword)){
    		return returnSuccess("一致");
    	}else{
            return JsonResult.createErrorMsg("不一致");
        }
    }
    
    @RequestMapping(value="/editLand")
    public @ResponseBody JsonResult editLand(Long tid){
    	boolean result = sysUserService.editLand(tid);
    	if(result){
            return returnSuccess("操作成功");
        }else{
            return JsonResult.createErrorMsg("操作失败");
        }
    }
    
} 
